package cn.myweixin.controller;


import javax.servlet.annotation.WebServlet;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
 
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.sinacloud.storage.StorageClient;

import cn.myweixin.util.Office2PDFUtil;
 
/**
 * Servlet implementation class UploadServlet
 */
@WebServlet("/UploadServlet")
public class UploadServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public UploadServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		 doPost(request, response); 
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		
		 //得到上传文件的保存目录，将上传的文件存放于WEB-INF目录下，不允许外界直接访问，保证上传文件的安全
		String savePath = this.getServletContext().getRealPath("/upload");
		String savePath1 = this.getServletContext().getRealPath("/pdf");
		System.out.println(savePath);
        File filem = new File(savePath);
        if(!filem.exists()&&!filem.isDirectory()){
            System.out.println("目录或文件不存在！");
            System.out.println("正在创建目录或文件..");
            filem.mkdir();
        }
        
        
        File filem1 = new File(savePath1);
        if(!filem1.exists()&&!filem1.isDirectory()){
            System.out.println("目录或文件不存在！");
            System.out.println("正在创建目录或文件..");
            filem1.mkdir();
        }
        
       
        
      //设置编码格式为utf-8
		  request.setCharacterEncoding("utf-8");
		  response.setCharacterEncoding("utf-8"); 
		  

		 
		  //获取session，保存进度和上传结果，上传结果初始值为NOK，当为Ok表示上传完成
		  HttpSession session=request.getSession();
		  session.setAttribute("prog", "0");
		  session.setAttribute("result", "NOK"); 
		  session.setAttribute("error", "");
		  String error="";
		  //给上传的文件设一个最大值，这里是不得超过50MB
		  int maxSize=50*1024*1024;
		  //创建工厂对象和文件上传对象
		  DiskFileItemFactory factory=new DiskFileItemFactory();
		  ServletFileUpload upload=new ServletFileUpload(factory);
		  upload.setHeaderEncoding("UTF-8");
		  
		  //3、判断提交上来的数据是否是上传表单的数据
          if(!upload.isMultipartContent(request)){
              //按照传统方式获取数据
              return;
          }
		  
		  try {
		   //解析上传请求
		   List items=upload.parseRequest(request);
		   Iterator itr=items.iterator();
		    
		   while(itr.hasNext()){
		    FileItem item=(FileItem)itr.next();
		    //判断是否为文件域
		    if(!item.isFormField()){
		     if(item.getName()!=null&&!item.getName().equals("")){
		      //获取上传文件大小和文件名称
		      long upFileSize=item.getSize();  
		      
		      String fileName=item.getName();
		      fileName = fileName.substring(fileName.lastIndexOf(File.separator)+1);
		     
		      
		      if(upFileSize>maxSize){
		       error="您上传的文件太大了，请选择不超过50MB的文件!";
		       break;
		      }
		    
		      InputStream is=item.getInputStream();
		      int length=0;
		      byte[] by=new byte[1024];
		      double persent=0;
		 
		      PrintWriter out=response.getWriter();
		      
		    //得到上传文件的扩展名
              String fileExtName = fileName.substring(fileName.lastIndexOf(".")+1);
              String  realpath="";
              if("pdf".equals(fileExtName)){
            	  realpath=savePath1+File.separator+fileName;
              }
             /* else if("doc".equals(fileExtName)||"docx".equals(fileExtName)||"xls".equals(fileExtName)||"xlsx".equals(fileExtName)||"ppt".equals(fileExtName)||"pptx".equals(fileExtName)){
            	  realpath=savePath+File.separator+fileName;
              }*/
              else{
            	 /* error="仅支持上传office文件及pdf!";
   		       break;*/
            	  realpath=savePath+File.separator+fileName;
            	  
              }
              FileOutputStream fos=new FileOutputStream(realpath);
		      
		      while((length=is.read(by))!=-1){
		       //计算文件进度
		       persent+=length/(double)upFileSize*100D;
		       fos.write(by, 0, length);
		      
		       session.setAttribute("prog", Math.round(persent)+""); 
		       Thread.sleep(10);
		      }
		      fos.close();
		      is.close();
		      item.delete();
		     /* 
		      if(!"pdf".equals(fileExtName))
		      Office2PDFUtil.office2PDF( realpath , savePath1);*/
		      
		      Thread.sleep(1000);
		     }
		     else{
		      error="没选择上传文件！";
		     }
		     
		    }
		   } 
		  } catch (Exception e) {
		   e.printStackTrace();
		   error="上传文件出现错误:"+e.getMessage();
		  }
		  if(!error.equals("")){ 
		   session.setAttribute("error", error);
		  }else{
		   session.setAttribute("result", "OK");
		  }
	}

	
	/*//生成上传文件的文件名，文件名以：uuid+"_"+文件的原始名称
    public String mkFileName(String fileName){
        return UUID.randomUUID().toString()+"_"+fileName;
    }
    public String mkFilePath(String savePath,String fileName){
        //得到文件名的hashCode的值，得到的就是filename这个字符串对象在内存中的地址
        int hashcode = fileName.hashCode();
        int dir1 = hashcode&0xf;
        int dir2 = (hashcode&0xf0)>>4;
        //构造新的保存目录
        String dir = savePath + "\\" + dir1 + "\\" + dir2;
        //File既可以代表文件也可以代表目录
        File file = new File(dir);
        if(!file.exists()){
            file.mkdirs();
        }
        return dir;
    }*/
}
